package com.zzh.compilation.test;

import java.util.List;

class Parser {
    private int kk = 0;
    private List<Word> tokens;
    private int currentIndex;

    public Parser(List<Word> tokens) {
        this.tokens = tokens;
        this.currentIndex = 0;
    }

    private Word getNextWord() {
        if (currentIndex < tokens.size()) {
            return tokens.get(currentIndex++);
        }
        return null;
    }

    private void lrParser() {
        Word word = getNextWord();
        if (word!= null && word.getTypeNum() == 1) {
            word = yucu();
            if (word!= null && word.getTypeNum() == 6) {
                word = getNextWord();
                if (word!= null && word.getTypeNum() == 0 && kk == 0) {
                    System.out.println("success");
                }
            } else {
                if (kk!= 1) {
                    System.out.println("lack END error!");
                }
                kk = 1;
            }
        } else {
            if (kk!= 1) {
                System.out.println("Begin error!");
            }
            kk = 1;
        }
    }

    private Word yucu() {
        Word word = statement();
        while (word!= null && word.getTypeNum() == 26) {
            word = statement();
        }
        return word;
    }

    private Word statement() {
        Word word = getNextWord();
        if (word!= null && word.getTypeNum() == 10) {
            word = getNextWord();
            if (word!= null && word.getTypeNum() == 18) {
                word = expression();
                return word;
            } else {
                System.out.println("assignment token error!");
                return null;
            }
        } else {
            System.out.println("statement error!");
            return null;
        }
    }

    private Word expression() {
        Word word = term();
        while (word!= null && (word.getTypeNum() == 13 || word.getTypeNum() == 14)) {
            word = term();
        }
        return word;
    }

    private Word term() {
        Word word = factor();
        while (word!= null && (word.getTypeNum() == 15 || word.getTypeNum() == 16)) {
            word = factor();
        }
        return word;
    }

    private Word factor() {
        Word word = getNextWord();
        if (word!= null && (word.getTypeNum() == 10 || word.getTypeNum() == 11)) {
            return getNextWord();
        } else if (word!= null && word.getTypeNum() == 27) {
            word = expression();
            if (word!= null && word.getTypeNum() == 28) {
                return getNextWord();
            } else {
                System.out.println(") error!");
                kk = 1;
                return null;
            }
        } else {
            System.out.println("expression error!");
            kk = 1;
            return null;
        }
    }

    public void parse() {
        lrParser();
    }
}